import {ActionReducerMapBuilder, AsyncThunk, Draft} from "@reduxjs/toolkit";
import {StatePageType} from "@/redux";
import {RequestStatus} from "@/redux/RequestStatus.ts";
import {JsonResult, PagingData, PagingResult} from "@/http";

/**
 * 构建异步分页action的处理器
 * @param builder 异步action构建器
 * @param action_ 需要指定的异步action
 */
export const builderPagingHandler = <T, > (builder: ActionReducerMapBuilder<StatePageType<T>>, action_: AsyncThunk<JsonResult<PagingResult<T>>, PagingData, any> ) => {
    builder.addCase(action_.pending, state => {
        state.loading = true;
        state.status = RequestStatus.PENDING;
    });
    builder.addCase(action_.rejected, state => {
        state.loading = true;
        state.status = RequestStatus.FAILED
    });
    builder.addCase(action_.fulfilled, (state, action) => {
        const { data, currentPage, pageSize, total, totalPage } = action.payload.data;
        // console.log(action.payload)
        if (!action.payload.success){
            state.loading = true;
            state.status = RequestStatus.FAILED;
            return;
        }
        state.loading = false;
        state.status = RequestStatus.SUCCESS;
        state.data = data as Draft<T[]>;
        state.currentPage = currentPage;
        state.pageSize = pageSize;
        state.total = total;
        state.totalPage = totalPage;
    });
};